package com.lazy.es.es_demo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import org.elasticsearch.action.bulk.BulkAction;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import static org.elasticsearch.common.xcontent.XContentFactory.*;

public class FirstDemo {
    private static Logger logger = LoggerFactory.getLogger(FirstDemo.class);
    private static AtomicInteger seq = new AtomicInteger(1);
    
    private Client client;
    
    public void init() {
        Settings settings = Settings.settingsBuilder()
                .put("cluster.name", "my-es").build();
        client = TransportClient.builder().settings(settings).build()
                .addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress("192.168.1.60", 9300)))
                ;
    }
    
    public void destroy() {
        if (client != null) {
            client.close();
            client = null;
        }
    }
    
    public void indexA() throws IOException {
        IndexResponse response = client.prepareIndex("twitter", "tweet", "1")
                .setSource(getTestData()
                          )
                .get();
        
        logger.info("result = {}", response);
        
    }
    
    public void getA () {
        GetResponse response = client.prepareGet("twitter", "tweet", "1")
                .setOperationThreaded(false)
                .get();
        logger.info("result = {}", response.getSourceAsString());
    }
    
    public void bulkAction() {
        long startTime = System.currentTimeMillis();
        BulkRequestBuilder bulkRequest = client.prepareBulk();
        
     // either use client#prepare, or use Requests# to directly build index/delete requests
        for (int i= 1; i<10000; i++) {
            
            bulkRequest.add(client.prepareIndex("twitter", "tweet", Integer.toString(seq.getAndIncrement()))
                    .setSource(getTestData())
                    );
        }
        
        BulkResponse bulkResponse = bulkRequest.get();
        if (bulkResponse.hasFailures()) {
            logger.info("result = {}", "hasFailures");
        } else {
            logger.info("result = {}", bulkResponse.getHeaders());
        }
        logger.info("takes time {}ms", (System.currentTimeMillis() - startTime));
    }
    
    public Map<String, Object> getTestData () {
        Map<String, Object> json = new HashMap<String, Object>();
        json.put("user","kimchy");
        json.put("postDate",new Date());
        json.put("message","trying out Elasticsearch");
        return json;
    }
    
    public static void main(String[] args) throws IOException{
        FirstDemo demo = new FirstDemo();
        demo.init();
        long startTime = System.currentTimeMillis();
        // demo.indexA();
        // demo.getA();
        for (int i = 0; i < 100; i++) {
            demo.bulkAction();
        }
        
        demo.destroy();
        
        long endTime = System.currentTimeMillis();
        logger.info("all take time {} ms", (endTime - startTime));
    }
}
